// src/store/slices/subscriptionSlice.ts
import { createSlice, createAsyncThunk, PayloadAction } from '@reduxjs/toolkit';
import billingService from '../../services/billingService';
import api from '../../services/api';
import { Product } from 'react-native-iap';
import { Platform } from 'react-native';

interface Subscription {
  plan: 'FREE' | 'BASIC' | 'PREMIUM';
  expiryTime: string | null;
  autoRenew: boolean;
  startDate: string | null;
  nextBillingDate: string | null;
  platform: 'android' | 'ios';
  productId: string | null;
  orderId: string | null;
}

interface SubscriptionState {
  subscription: Subscription | null;
  products: Product[];
  isLoading: boolean;
  isPurchasing: boolean;
  error: string | null;
  purchaseHistory: any[];
  billingInfo: {
    paymentMethod: string | null;
    lastPaymentDate: string | null;
    totalSpent: number;
  };
}

const initialState: SubscriptionState = {
  subscription: {
    plan: 'FREE',
    expiryTime: null,
    autoRenew: false,
    startDate: null,
    nextBillingDate: null,
    platform: Platform.OS as 'android' | 'ios',
    productId: null,
    orderId: null,
  },
  products: [],
  isLoading: false,
  isPurchasing: false,
  error: null,
  purchaseHistory: [],
  billingInfo: {
    paymentMethod: null,
    lastPaymentDate: null,
    totalSpent: 0,
  },
};

// 异步actions
export const loadProducts = createAsyncThunk('subscription/loadProducts', async () => {
  const products = await billingService.getSubscriptions();
  return products;
});

export const purchaseSubscription = createAsyncThunk(
  'subscription/purchase',
  async (productId: string) => {
    await billingService.purchaseSubscription(productId);
    const status = await billingService.getSubscriptionStatus();
    return status;
  }
);

export const restorePurchases = createAsyncThunk('subscription/restore', async () => {
  const purchases = await billingService.restorePurchases();
  const status = await billingService.getSubscriptionStatus();
  return { purchases, status };
});

export const cancelSubscription = createAsyncThunk('subscription/cancel', async () => {
  await billingService.cancelSubscription();
  return null;
});

export const loadSubscriptionStatus = createAsyncThunk(
  'subscription/loadStatus',
  async () => {
    const response = await api.get('/api/subscription/status');
    return response.data;
  }
);

export const loadPurchaseHistory = createAsyncThunk(
  'subscription/loadHistory',
  async () => {
    const response = await api.get('/api/subscription/history');
    return response.data;
  }
);

const subscriptionSlice = createSlice({
  name: 'subscription',
  initialState,
  reducers: {
    updateSubscription: (state, action: PayloadAction<Partial<Subscription>>) => {
      state.subscription = {
        ...state.subscription!,
        ...action.payload,
      };
    },
    setProducts: (state, action: PayloadAction<Product[]>) => {
      state.products = action.payload;
    },
    clearError: (state) => {
      state.error = null;
    },
    resetSubscription: () => initialState,
  },
  extraReducers: (builder) => {
    builder
      // Load Products
      .addCase(loadProducts.pending, (state) => {
        state.isLoading = true;
        state.error = null;
      })
      .addCase(loadProducts.fulfilled, (state, action) => {
        state.isLoading = false;
        state.products = action.payload;
      })
      .addCase(loadProducts.rejected, (state, action) => {
        state.isLoading = false;
        state.error = action.error.message || '加载产品失败';
      })
      // Purchase Subscription
      .addCase(purchaseSubscription.pending, (state) => {
        state.isPurchasing = true;
        state.error = null;
      })
      .addCase(purchaseSubscription.fulfilled, (state, action) => {
        state.isPurchasing = false;
        state.subscription = {
          ...state.subscription!,
          ...action.payload,
        };
      })
      .addCase(purchaseSubscription.rejected, (state, action) => {
        state.isPurchasing = false;
        state.error = action.error.message || '购买失败';
      })
      // Restore Purchases
      .addCase(restorePurchases.pending, (state) => {
        state.isLoading = true;
      })
      .addCase(restorePurchases.fulfilled, (state, action) => {
        state.isLoading = false;
        state.subscription = {
          ...state.subscription!,
          ...action.payload.status,
        };
      })
      .addCase(restorePurchases.rejected, (state, action) => {
        state.isLoading = false;
        state.error = action.error.message || '恢复失败';
      })
      // Cancel Subscription
      .addCase(cancelSubscription.fulfilled, (state) => {
        state.subscription = {
          ...state.subscription!,
          autoRenew: false,
        };
      })
      // Load Status
      .addCase(loadSubscriptionStatus.fulfilled, (state, action) => {
        state.subscription = action.payload;
      })
      // Load History
      .addCase(loadPurchaseHistory.fulfilled, (state, action) => {
        state.purchaseHistory = action.payload.history;
        state.billingInfo = action.payload.billingInfo;
      });
  },
});

export const {
  updateSubscription,
  setProducts,
  clearError,
  resetSubscription,
} = subscriptionSlice.actions;

export default subscriptionSlice.reducer;